{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Callback duration\n",
    "#\n",
    "# Get trace data using the provided launch file:\n",
    "#    $ ros2 launch tracetools_analysis pingpong.launch.py\n",
    "#    (wait at least a few seconds, then kill with Ctrl+C)\n",
    "#\n",
    "# OR\n",
    "#\n",
    "# Use the provided sample converted trace file, changing the path below to:\n",
    "#    'sample_data/converted_pingpong'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "path = '~/.ros/tracing/pingpong/ust'\n",
    "#path = 'sample_data/converted_pingpong'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "# Add paths to tracetools_analysis and tracetools_read.\n",
    "# There are two options:\n",
    "#   1. from source, assuming a workspace with:\n",
    "#       src/tracetools_analysis/\n",
    "#       src/ros2/ros2_tracing/tracetools_read/\n",
    "sys.path.insert(0, '../')\n",
    "sys.path.insert(0, '../../../ros2/ros2_tracing/tracetools_read/')\n",
    "#   2. from Debian packages, setting the right ROS 2 distro:\n",
    "#ROS_DISTRO = 'rolling'\n",
    "#sys.path.insert(0, f'/opt/ros/{ROS_DISTRO}/lib/python3.8/site-packages')\n",
    "import datetime as dt\n",
    "\n",
    "from bokeh.plotting import figure\n",
    "from bokeh.plotting import output_notebook\n",
    "from bokeh.io import show\n",
    "from bokeh.layouts import row\n",
    "from bokeh.models import ColumnDataSource\n",
    "from bokeh.models import DatetimeTickFormatter\n",
    "from bokeh.models import PrintfTickFormatter\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "from tracetools_analysis.loading import load_file\n",
    "from tracetools_analysis.processor.ros2 import Ros2Handler\n",
    "from tracetools_analysis.utils.ros2 import Ros2DataModelUtil"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Process\n",
    "events = load_file(path)\n",
    "handler = Ros2Handler.process(events)\n",
    "#handler.data.print_data()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data_util = Ros2DataModelUtil(handler.data)\n",
    "\n",
    "callback_symbols = data_util.get_callback_symbols()\n",
    "\n",
    "output_notebook()\n",
    "psize = 450\n",
    "colours = ['#29788E', '#DD4968', '#410967']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Plot durations separately\n",
    "colour_i = 0\n",
    "for obj, symbol in callback_symbols.items():\n",
    "    owner_info = data_util.get_callback_owner_info(obj)\n",
    "    if owner_info is None:\n",
    "        owner_info = '[unknown]'\n",
    "\n",
    "    # Filter out internal subscriptions\n",
    "    if '/parameter_events' in owner_info:\n",
    "        continue\n",
    "\n",
    "    # Duration\n",
    "    duration_df = data_util.get_callback_durations(obj)\n",
    "    starttime = duration_df.loc[:, 'timestamp'].iloc[0].strftime('%Y-%m-%d %H:%M')\n",
    "    source = ColumnDataSource(duration_df)\n",
    "    duration = figure(\n",
    "        title=owner_info,\n",
    "        x_axis_label=f'start ({starttime})',\n",
    "        y_axis_label='duration (ms)',\n",
    "        width=psize, height=psize,\n",
    "    )\n",
    "    duration.title.align = 'center'\n",
    "    duration.line(\n",
    "        x='timestamp',\n",
    "        y='duration',\n",
    "        legend_label=str(symbol),\n",
    "        line_width=2,\n",
    "        source=source,\n",
    "        line_color=colours[colour_i],\n",
    "    )\n",
    "    duration.legend.label_text_font_size = '11px'\n",
    "    duration.xaxis[0].formatter = DatetimeTickFormatter(seconds='%Ss')\n",
    "\n",
    "    # Histogram\n",
    "    # (convert to milliseconds)\n",
    "    dur_hist, edges = np.histogram(duration_df['duration'] * 1000 / np.timedelta64(1, 's'))\n",
    "    duration_hist = pd.DataFrame({\n",
    "        'duration': dur_hist, \n",
    "        'left': edges[:-1], \n",
    "        'right': edges[1:],\n",
    "    })\n",
    "    hist = figure(\n",
    "        title='Duration histogram',\n",
    "        x_axis_label='duration (ms)',\n",
    "        y_axis_label='frequency',\n",
    "        width=psize, height=psize,\n",
    "    )\n",
    "    hist.title.align = 'center'\n",
    "    hist.quad(\n",
    "        bottom=0,\n",
    "        top=duration_hist['duration'], \n",
    "        left=duration_hist['left'],\n",
    "        right=duration_hist['right'],\n",
    "        fill_color=colours[colour_i],\n",
    "        line_color=colours[colour_i],\n",
    "    )\n",
    "\n",
    "    colour_i += 1\n",
    "    show(row(duration, hist))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Plot durations in one plot\n",
    "earliest_date = None\n",
    "for obj, symbol in callback_symbols.items():\n",
    "    duration_df = data_util.get_callback_durations(obj)\n",
    "    thedate = duration_df.loc[:, 'timestamp'].iloc[0]\n",
    "    if earliest_date is None or thedate <= earliest_date:\n",
    "        earliest_date = thedate\n",
    "\n",
    "starttime = earliest_date.strftime('%Y-%m-%d %H:%M')\n",
    "duration = figure(\n",
    "    title='Callback durations',\n",
    "    x_axis_label=f'start ({starttime})',\n",
    "    y_axis_label='duration (ms)',\n",
    "    width=psize, height=psize,\n",
    ")\n",
    "\n",
    "colour_i = 0\n",
    "for obj, symbol in callback_symbols.items():\n",
    "    # Filter out internal subscriptions\n",
    "    owner_info = data_util.get_callback_owner_info(obj)\n",
    "    if not owner_info or '/parameter_events' in owner_info:\n",
    "        continue\n",
    "\n",
    "    duration_df = data_util.get_callback_durations(obj)\n",
    "    source = ColumnDataSource(duration_df)\n",
    "    duration.title.align = 'center'\n",
    "    duration.line(\n",
    "        x='timestamp',\n",
    "        y='duration',\n",
    "        legend_label=str(symbol),\n",
    "        line_width=2,\n",
    "        source=source,\n",
    "        line_color=colours[colour_i],\n",
    "    )\n",
    "    colour_i += 1\n",
    "    duration.legend.label_text_font_size = '11px'\n",
    "    duration.xaxis[0].formatter = DatetimeTickFormatter(seconds='%Ss')\n",
    "\n",
    "show(duration)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
